/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.user.rest;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.common.aop.NoRepeatSubmit;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.interceptor.AuthCheck;
import co.yixiang.constant.ShopConstants;
import co.yixiang.constant.SystemConfigConstants;
import co.yixiang.enums.BillDetailEnum;
import co.yixiang.logging.aop.log.AppLog;
import co.yixiang.modules.activity.domain.YxUserExtract;
import co.yixiang.modules.activity.service.YxUserExtractService;
import co.yixiang.modules.mp.domain.YxWechatLive;
import co.yixiang.modules.mp.service.YxWechatLiveService;
import co.yixiang.modules.product.domain.YxTestQuestion;
import co.yixiang.modules.product.domain.YxTestQuestionDetail;
import co.yixiang.modules.product.domain.YxTestQuestionRecord;
import co.yixiang.modules.product.domain.YxTestQuestionType;
import co.yixiang.modules.product.service.YxTestQuestionDetailService;
import co.yixiang.modules.product.service.YxTestQuestionRecordService;
import co.yixiang.modules.product.service.YxTestQuestionService;
import co.yixiang.modules.product.service.YxTestQuestionTypeService;
import co.yixiang.modules.services.CreatShareProductService;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.param.PromParam;
import co.yixiang.modules.user.param.TestQuestion;
import co.yixiang.modules.user.param.TestQuestionParam;
import co.yixiang.modules.user.param.YxUserBillQueryParam;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.vo.BillVo;
import co.yixiang.modules.user.vo.YxUserBillQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName UserBillController
 * @Author hupeng <610796224@qq.com>
 * @Date 2019/11/10
 **/
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "试题", tags = "试题", description = "试题")
public class TestQuestionController {

    private final YxTestQuestionService testQuestionService;
    private final YxTestQuestionDetailService testQuestionDetailService;
    private final YxTestQuestionTypeService testQuestionTypeService;
    private final YxUserService yxUserService;
    private final CreatShareProductService creatShareProductService;
    private final YxTestQuestionRecordService testQuestionRecordService;

    @Value("${file.path}")
    private String path;



    @AppLog(value = "考试列表", type = 1)
    @AuthCheck
    @GetMapping("/question/getQuestionList/{typeId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码,默认为1", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "页大小,默认为10", paramType = "query", dataType = "int"),
    })
    @ApiOperation(value = "考试列表",notes = "考试列表")
    public ApiResult<Object> operate4cityDayCommission(@RequestParam(value = "page",defaultValue = "1") int page,
                                                    @RequestParam(value = "limit",defaultValue = "10") int limit,
                                                    @PathVariable String typeId){
        List<YxTestQuestion> questionList =testQuestionService.list(new LambdaQueryWrapper<YxTestQuestion>()
                .eq(YxTestQuestion ::getQuestionTypeId,Long.valueOf(typeId)).orderByAsc(YxTestQuestion ::getSort));
        if(questionList.size()>0){
            for(YxTestQuestion question:questionList){
                List<YxTestQuestionDetail> detailList =testQuestionDetailService.list(new LambdaQueryWrapper<YxTestQuestionDetail>()
                        .eq(YxTestQuestionDetail ::getQuestionId,question.getId()).orderByAsc(YxTestQuestionDetail ::getSort));
                question.setDetailList(detailList);
            }
        }
        YxTestQuestionType typeVo =testQuestionTypeService.getById(Long.valueOf(typeId));
        Map<String,Object> map = new LinkedHashMap<>();
        //double totalSum =userBillService.operateCommissionSum(uid,areaName);
        //double monthTotalSum =userBillService.operate4monthCommissionSum(uid,filterBtnstartDate,areaName);
        //map.put("totalSum",totalSum);
        //map.put("monthTotalSum",monthTotalSum);
        map.put("list",questionList);
        map.put("questionType",typeVo);
        return ApiResult.ok(map);
    }

    @AppLog(value = "插入考试记录", type = 0)
    @NoRepeatSubmit
    @AuthCheck
    @PostMapping("/question/saveQuestion")
    @ApiOperation(value = "插入考试记录",notes = "插入考试记录")
    public ApiResult<Object> saveReserved(@RequestBody TestQuestionParam param) throws Exception{
        Map<String,Object> map = new LinkedHashMap<>();
        Long uid = LocalUser.getUser().getUid();
        //Long uid =2617L;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date =new Date();
        String timeDate =sdf.format(date);
        YxTestQuestionType type =testQuestionTypeService.getById(Long.valueOf(param.getTypeId()));
        List<TestQuestion> list =param.getQuestionArr();
        List<YxTestQuestionRecord> questionList =testQuestionRecordService.list(new LambdaQueryWrapper<YxTestQuestionRecord>()
                .eq(YxTestQuestionRecord ::getQuestionTypeId,Long.valueOf(param.getTypeId()))
                .eq(YxTestQuestionRecord ::getUid,uid)
                 .apply("DATE_FORMAT(create_time,'%Y-%m-%d')='"+timeDate+"'")
                );
        BigDecimal totalGrade =BigDecimal.ZERO;
        String isPass ="N";
        String isLimit ="N";
        if(questionList.size()>=type.getLimitCount()){
            isLimit ="Y";
        }else{
            if(list.size()>0){
                for(int i=0;i<list.size();i++){
                    TestQuestion tq =list.get(i);
                    YxTestQuestionDetail detail =testQuestionDetailService.getById(tq.getId());
                    YxTestQuestion question =testQuestionService.getById(tq.getQuestionId());
                    if(detail.getIsCorrect().intValue() ==1){
                        totalGrade =totalGrade.add(new BigDecimal(question.getGrade()));
                    }
                }
            }
            YxUser user =yxUserService.getById(uid);
            YxTestQuestionRecord yqr =new YxTestQuestionRecord();
            yqr.setQuestionTypeId(type.getId());
            yqr.setQuestionTypeName(type.getQuestionName());
            yqr.setUid(uid);
            yqr.setUserPhone(user.getPhone());
            yqr.setNickname(user.getNickname());
            yqr.setHeadimgurl(user.getAvatar());
            yqr.setLevel(user.getLevel());
            yqr.setAdoptGrade(type.getTotalScore());
            yqr.setTotalGrade(totalGrade);
            if(totalGrade.compareTo(type.getTotalScore()) !=-1){
                if(type.getQuestionName().contains("晋升")){
                    user.setIsPromotionPass("Y");
                }else{
                    user.setIsOpenLian("Y");
                }
                yxUserService.updateById(user);
                isPass ="Y";
                yqr.setIsAdopt(1);
            }
            testQuestionRecordService.save(yqr);
        }
        map.put("isPass",isPass);
        map.put("totalGrade",totalGrade);
        map.put("isLimit",isLimit);
        return ApiResult.ok(map);
    }




}
